
import json
from config import TeamConfig, SongConfig
from card import Card
import os
import codecs
import operator
song = SongConfig()

from PIL import Image, ImageDraw, ImageFont

levels = {
    "low": 1,
    "mid-low": 4,
    "mid-high": 4,
    "high": 2,
    "very-high": 1
}
levels_total = 12
timestamp = "2022.11.22"
accessory_levels = ["low", "normal", "high"]
difficulties = ["上级", "上级+", "无上限"]
base_damage = {
    "上级": 1300,
    "上级+": 2500,
    "无上限": 3000,
}
colors = {
    "粉": (220,140,140),
    "绿": (0,255,0),
    "蓝": (0,0,255),
    "红": (255,0,0),
    "黄": (200,200,0),
    "紫": (135,30,125),
}
full_names = {
    "果": ["001", "高坂穗乃果"],
    "绘": ["002", "绚濑绘里"],
    "鸟": ["003", "南小鸟"],
    "海": ["004", "园田海未"],
    "凛": ["005", "星空凛"],
    "姬": ["006", "西木野真姬"],
    "希": ["007", "东条希"],
    "花": ["008", "小泉花阳"],
    "妮": ["009", "矢泽妮可"],
    "千": ["101", "高海千歌"],
    "梨": ["102", "樱内梨子"],
    "南": ["103", "松浦果南"],
    "黛": ["104", "黑泽黛雅"],
    "曜": ["105", "渡边曜"],
    "善": ["106", "津岛善子"],
    "丸": ["107", "国木田花丸"],
    "鞠": ["108", "小原鞠莉"],
    "露": ["109", "黑泽露比"],
    "步": ["201", "上原步梦"],
    "霞": ["202", "中须霞"],
    "雫": ["203", "樱坂雫"],
    "林": ["204", "朝香果林"],
    "爱": ["205", "宫下爱"],
    "彼": ["206", "近江彼方"],
    "菜": ["207", "优木雪菜"],
    "艾": ["208", "艾玛·维尔德"],
    "璃": ["209", "天王寺璃奈"],
    "栞": ["210", "三船栞子"],
    "米": ["211", "米亚·泰勒"],
    "钟": ["212", "钟岚珠"]
}
card_levels = ["S", "A+", "A", "B+", "B", "C+", "C"]
levels_score = {
    "上级输出": {"S": 108, "A+": 105, "A": 102, "B+": 99, "B": 96, "C+": 93, "C": 90},
    "上级+输出": {"S": 102, "A+": 97, "A": 92, "B+": 87, "B": 82, "C+": 77, "C": 72},
    "无上限输出": {"S": 95, "A+": 90, "A": 85, "B+": 80, "B": 75, "C+": 70, "C": 65},
    "后排辅助": {"S+": 0.12, "S": 0.11, "A+": 0.098, "A": 0.085, "B+": 0.078, "B": 0.07, "C+": 0.06, "C": 0.05},
    "后排爆分": {"S": 80, "A+": 70, "A": 60, "B+": 50, "B": 40},
    "前排奶盾": {"S": 90, "A+": 80, "A": 70, "B+": 60, "B": 50, "C+": 40, "C": 30},
    "切队奶盾": {"S": 75, "A+": 67, "A": 60, "B+": 52, "B": 45},
    "后排奶盾": {"S": 180, "A+": 160, "A": 140, "B+": 120, "B": 100, "C+": 80, "C": 60},
    "减伤": {"S": 50, "A+": 45, "A": 40, "B+": 35, "B": 30, "C+": 25, "C": 20}
}
ranking_levels = ["T0", "T0.5", "T1", "T1.5", "T2", "T2.5", "T3", "T3.5", "T4"]
ranking_scores = {
    "T0": 110,
    "T0.5": 100,
    "T1": 90,
    "T1.5": 80,
    "T2": 70,
    "T2.5": 60,
    "T3": 50,
    "T3.5": 40,
    "T4": 0
}
colors = ["粉", "绿", "蓝", "红", "黄", "紫"]

def print_level(card, diffculty):
    print(card.name, difficulty)
    for level in levels.keys():
        print(level, card.debug[diffculty]["power_by_level"][level])

def get_block(card_name, caption, font_size=10, idolized=True):
    result = '<div style="display:inline-block;margin-right:5px"><figure style="margin:0px;margin-top:2px"><img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/card-avatar/'
    result += card_name + ("" if idolized else "未觉") + '.jpg" width="60" alt="'+ card_name +'"></figure><figcaption style="text-align:center;margin-bottom:5px;line-height:13px;font-size:12px">'+caption +'</figcaption></div>'
    return result

def generate_ranking_md(cards, ranking_type="上级输出", color=None):
    card_levels = ["S", "A+", "A", "B+", "B"]
    difficulty = ranking_type.replace("输出", "")
    cards = sorted(cards, key=lambda x: x.power[difficulty]["average"], reverse=True)
    card_pos = 0
    result = ""

    result += "| 档位 | " + ranking_type + " |\n"
    result += "| ---- | ---- |\n"
    for level in card_levels:
        result += "|" + level + "|"
        while card_pos < len(cards):
            card = cards[card_pos]
            if card.power[difficulty]["average"] < levels_score[ranking_type][level] * base_damage[difficulty]:
                break
            if card.color == color or not color:
                caption = str(round(card.power[difficulty]["average"] / base_damage[difficulty], 1))+ "<br>("
                caption += str(int(card.power[difficulty]["low"] / base_damage[difficulty]))+ "→" + str(int(card.power[difficulty]["very-high"] / base_damage[difficulty]))
                caption += ")"
                result += get_block(card.name, caption)
            card_pos += 1
        result += "|\n"
    return result

def get_support(card, color=None, is_max=False):
    postfix = ""
    if is_max:
        postfix = "_max"
    if not color or card.color != color :
        return (card.support["上级"]["all" + postfix] + card.support["上级+"]["all" + postfix])/2
    else:
        return (card.support["上级"]["same_attribute" + postfix] + card.support["上级+"]["same_attribute" + postfix])/2

def generate_support_ranking_md(cards, color=None):
    card_levels = ["S", "A+", "A", "B+", "B"]
    result = ""

    cards = sorted(cards, key=lambda x: get_support(x, color), reverse=True)
    cards_upper_bound = sorted(cards, key=lambda x: get_support(x, color, True), reverse=True)
    card_pos = 0
    card_upper_pos = 0
    result += "| 档位 | 后排辅助 |\n"
    result += "| ---- | ---- |\n"
    for level in card_levels:
        result += "|" + level + "|"
        while card_pos < len(cards) and card_upper_pos < len(cards_upper_bound):
            card = cards[card_pos]
            card_upper = cards_upper_bound[card_upper_pos]
            need_upper = False
            if get_support(card_upper, color, True) < levels_score["后排辅助"][level] and get_support(card, color) < levels_score["后排辅助"][level]:
                break
            if get_support(card, color) < get_support(card_upper, color, True):
                need_upper = True
            if need_upper:
                #if card.color == color or not color:
                if get_support(card_upper, color, True) - get_support(card_upper, color) > 0.005:
                    caption = "上限" + str(round(100 * get_support(card_upper, color, True), 1)) + "%"
                    result += get_block(card_upper.name, caption)
                card_upper_pos += 1
            else:
                #if card.color == color or not color:
                if get_support(card, color, True) - get_support(card, color) > 0.005:
                    caption = "平均" + str(round(100 * get_support(card, color), 1)) + "%"
                else:
                    caption = str(round(100 * get_support(card, color), 1)) + "%"
                result += get_block(card.name, caption)
                card_pos += 1
        result += "|\n"
    return result

def get_back_heal(card):
    return (card.heal["上级"]["back"] + card.heal["上级+"]["back"]) / 2

def generate_back_healer_md(cards, color=None):
    card_levels = ["S", "A+", "A", "B+", "B", "C+", "C"]

    cards = sorted(cards, key=lambda x: get_back_heal(x), reverse=True)
    card_pos = 0
    result = ""

    result += "| 档位 | 后排奶盾 |\n"
    result += "| ---- | ---- |\n"
    for level in card_levels:
        result += "|" + level + "|"
        while card_pos < len(cards):
            card = cards[card_pos]
            if card.name == "花园绘":
                card_pos += 1
                continue
            if get_back_heal(card) < levels_score["后排奶盾"][level]:
                break
            caption = str(round(get_back_heal(card)))
            result += get_block(card.name, caption)
            card_pos += 1
        result += "|\n"
    return result

def generate_main_healer_md(cards, color=None):
    card_levels = ["S", "A+", "A", "B+", "B", "C+", "C"]

    cards = sorted(cards, key=lambda x: x.get_heal_main(), reverse=True)
    card_pos = 0
    result = ""

    result += "| 档位 | 前排奶盾 |\n"
    result += "| ---- | ---- |\n"
    for level in card_levels:
        result += "|" + level + "|"
        while card_pos < len(cards):
            card = cards[card_pos]
            if card.get_heal_main() < levels_score["前排奶盾"][level]:
                break
            if card.color == color or not color:
                caption = str(round(card.get_heal_main()))
                result += get_block(card.name, caption)
            card_pos += 1
        result += "|\n"
    return result

def generate_swap_healer_md(cards, color=None):
    card_levels = ["S", "A+", "A", "B+", "B"]

    cards = sorted(cards, key=lambda x: x.get_heal_swap(), reverse=True)
    card_pos = 0
    result = ""

    result += "| 档位 | 切队奶盾 |\n"
    result += "| ---- | ---- |\n"
    for level in card_levels:
        result += "|" + level + "|"
        while card_pos < len(cards):
            card = cards[card_pos]
            if card.get_heal_swap() < levels_score["切队奶盾"][level]:
                break
            if card.color == color or not color:
                caption = str(round(card.get_heal_swap()))
                result += get_block(card.name, caption)
            card_pos += 1
        result += "|\n"
    return result

def generating_final_ranking_md(cards, character=None, idolized=True):
    card_levels = ranking_levels
    cards = sorted(cards, key=lambda x: x.final_score, reverse=True)
    card_pos = 0

    result = "| 档位 | 综合评分 |\n"
    result += "| ---- | ---- |\n"
    for level in card_levels:
        result += "|" + level + "|"
        while card_pos < len(cards):
            card = cards[card_pos]
            if character and card.name[-1] != character:
                card_pos += 1
                continue
            if card.final_score < ranking_scores[level]:
                break
            #if card.color == color or not color:
            caption = str(round(card.final_score, 1))
            result += get_block(card.name, caption, idolized=idolized)
            card_pos += 1
        result += "|\n"
    return result

def get_kizuna_value_text(card):
    caption = "很低"
    if card.get_value() >= 2.:
        caption = '<b style="color:red">超高</b>'
    elif card.get_value() >= 1.5:
        caption = '<b style="color:red">很高</b>'
    elif card.get_value() >= 1.:
        caption = '<b style="color:red">较高</b>'
    elif card.get_value() >= 0.6:
        caption = "中上"
    elif card.get_value() >= 0.3:
        caption = "中等"
    elif card.get_value() >= 0.1:
        caption = "略有"
    return caption

def get_score_level(score_levels, score, levels):
    for level in levels:
        if level in score_levels.keys() and score >= score_levels[level]:
            return level
    return "-"

def generate_kizuna_value_md(cards, characters_list):
    result = ""
    result += "| 排名 | 角色 | 卡片 |\n"
    result += "| ---- | ---- | ---- |\n"

    count = 0
    for character in characters_list:
        count += 1
        result += "| " + str(count) + "| " + "![image](https://llas-1315296209.cos.ap-shanghai.myqcloud.com/characters/"+character["character"] +".png)|"
        character["cards"] = sorted(character["cards"], key=lambda x: x.get_value(), reverse=True)
        for card in character["cards"]:
            if card.get_value() <= 0.1:
                continue
            caption = get_kizuna_value_text(card)
            result += get_block(card.name, caption + "<br>" + str(round(card.get_value(), 2)))
        result += "|\n"

    #result += ""
    # 表尾
    return result

def skill_text(skill_type, effect, scope="", limit=0, notes=0):
    result = ""
    if notes > 0:
        result += str(notes) + "个键内"
    if skill_type == "st奶":
        result += '回复自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/绿值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的血量'
    if skill_type == "st奶每gd":
        result += '回复' + str(round(effect)) + '*队中gd数量的血量'
    if skill_type == "st盾":
        result += '获得自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/绿值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的护盾'
    if skill_type == "te奶":
        result += '回复自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/黄值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的血量'
    if skill_type == "te盾":
        result += '获得自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/黄值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的护盾'
    if skill_type == "ap盾":
        result += '获得自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的护盾'
    if skill_type == "暴击率":
        try:
            result += '暴击率增加' + str(round(100 * effect, 1)) + '%'
        except:
            pass
    if skill_type == "暴伤":
        result += '暴击伤害增加' + str(round(100 * effect, 1)) + '%'
    if skill_type == "快充":
        result += '获得最大SP的' + str(round(100 * effect, 1)) + '%的SP'
    if skill_type == "慢充":
        result += 'SP获得量提升' + str(round(100 * effect, 1)) + '%'
    if skill_type == "sp获得":
        result += "获得" + str(int(effect)) + '点SP'
    if skill_type == "ap快充":
        result += '获得自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的SP'
    if skill_type == "te快充":
        result += '获得自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/黄值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的SP'
    if skill_type == "vo":
        result += '按键得分增加' + str(round(100 * effect, 1)) + '%'
    if skill_type == "ap每vo":
        result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>增加' + str(round(100 * effect, 1)) + '%*队中vo数量'
    if skill_type == "ap":
        result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>增加' + str(round(100 * effect, 1)) + '%'
    if skill_type == "特殊ap":
        result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>（特殊）增加' + str(round(100 * effect, 1)) + '%'
    if skill_type == "apup":
        result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>提升' + str(round(100 * effect, 1)) + '%'
    if skill_type == "ap爆分":
        result += '获得自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的得分'
    if skill_type == "st爆分":
        result += '获得自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/绿值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的得分'
    if skill_type == "te爆分":
        result += '获得自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/黄值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的得分'
    if skill_type == "ap核爆":
        result += '下次SP得分增加自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的得分'
    if skill_type == "te核爆":
        result += '下次SP得分增加自身<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/黄值.png" width="20px"/>的' + str(round(100 * effect, 1)) + '%的得分'
    if skill_type == "特技":
        result += '特技发动率增加' + str(round(100 * effect, 1)) + '%'
    if skill_type == "减伤":
        result += '减伤' + str(round(100 * effect, 1)) + '%'
    if skill_type == "超充":
        result += '与歌曲同属性时，SP槽可以溢出至200%，根据SP消耗量，SP特技得分最多增加' + str(round(100 * effect, 1)) + '%'
    if skill_type == "超限":
        result += '暴击时得分上限增加' + str(round(100 * effect, 1)) + '%'
    if skill_type == "驱散":
        result += '解除所有debuff（基本除外）'
    if skill_type == "gd切队效果":
        result += 'gd类型切队效果提升' + str(round(100 * effect, 1)) + '%'
    if limit > 0:
        result += "，限" + str(limit) + "次"
    if scope:
        result += "（对象：" + scope + "）"
    return result

def format_score_level(score_level):
    if "S" in score_level:
        return '<span style="color:red">' + score_level + '</span>'
    return score_level


color_code = {
    "粉": "pink",
    "绿": "green",
    "蓝": "blue",
    "红": "red",
    "黄": "yellow",
    "紫": "purple"
}

assess_level = {
    "S": "超强",
    "A+": "很强",
    "A": "较强",
    "B+": "一般",
    "B": "一般",
    "C+": "凑合",
    "C": "凑合"
}

def get_assessment(card):
    scores = sorted(card.scores.items(), key=operator.itemgetter(1), reverse=True)
    result = ""
    max_score = scores[0][1]
    for score in scores:
        if max_score - score[1] > 20:
            continue
        if score[0] == "上级+输出":
            score_tmp = card.power['上级+']["average"] / base_damage['上级+']
            level = get_score_level(levels_score["上级+输出"], score_tmp, card_levels)
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的上+前排输出"
        if score[0] == "上级输出":
            score_tmp = card.power['上级']["average"] / base_damage['上级']
            level = get_score_level(levels_score["上级输出"], score_tmp, card_levels) 
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的上级前排输出"
        if score[0] == "前排奶盾":
            score_tmp = card.get_heal_main()
            level = get_score_level(levels_score["前排奶盾"], score_tmp, card_levels) 
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的前排奶盾"
        if score[0] == "切队奶盾":
            score_tmp = card.get_heal_swap()
            level = get_score_level(levels_score["切队奶盾"], score_tmp, card_levels) 
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的切队奶盾"
        if score[0] == "后排奶盾":
            score_tmp = (card.heal["上级"]["back"] + card.heal["上级+"]["back"]) / 2
            level = get_score_level(levels_score["后排奶盾"], score_tmp, card_levels) 
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的后排奶盾"
        if score[0] == "通用后排辅助":
            score_tmp = card.get_support_all()
            level = get_score_level(levels_score["后排辅助"], score_tmp, card_levels) 
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的通用后排辅助"
        if score[0] == "同属性后排辅助" and score[1] > card.scores["通用后排辅助"]:
            score_tmp = card.get_support_same_attribute()
            level = get_score_level(levels_score["后排辅助"], score_tmp, card_levels) 
            if level != "-" and "C" not in level:
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的" + card.color + "队后排辅助"
        if score[0] == "通用后排爆分":
            score_tmp = card.get_support_scoring_all(card.get_support_all())
            level = get_score_level(levels_score["后排爆分"], score_tmp, card_levels) 
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的通用后排充能/爆分"
        if score[0] == "同属性后排爆分" and score[1] > card.scores["通用后排爆分"]:
            score_tmp = card.get_support_scoring_same_attribute(card.get_support_same_attribute())
            level = get_score_level(levels_score["后排爆分"], score_tmp, card_levels) 
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的" + card.color + "歌后排充能/爆分"
        if score[0] == "减伤":
            score_tmp = card.scores["减伤"]
            level = get_score_level(levels_score["减伤"], score_tmp, card_levels) 
            if level != "-":
                result += ("，" if len(result) > 0 else "") + assess_level[level] + "的减伤"
        if score[0] == "SBL抢赏" and score[1] >= 30.:
            result += ("，" if len(result) > 0 else "") + "SBL抢赏"
        if score[0] == "千伤回血" and score[1] >= 30.:
            result += ("，" if len(result) > 0 else "") + "单键伤害超过1000时的后排奶"
        if score[0] == "同学校后排辅助爆分" and score[1] >= 30.:
            result += ("，" if len(result) > 0 else "") + "同学校后排辅助爆分"
        if score[0] == "驱散" and score[1] >= 30.:
            result += ("，" if len(result) > 0 else "") + "驱散"
        if score[0] == "超充" and score[1] >= 30.:
            result += ("，" if len(result) > 0 else "") + "超充"
    if len(result) == 0:
        return "几乎没有什么作用的卡"
    return result

def append_inspiration(result, inspiration):
    if len(result) > 0:
        result += "、"
    result += inspiration.replace("红值", '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/合宿红值.png" width="20px"/>').replace("特技", '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/合宿特技.png" width="20px"/>')
    return result

def generate_inspirations(card):
    result = ""
    if not card.diff_inspirations:
        for inspiration in card.best_inspirations:
            result = append_inspiration(result, inspiration)
    else:
        result = "视实际用途刷"
        if len(card.best_inspirations) > 0:
            best_result = ""
            for inspiration in card.best_inspirations:
                best_result = append_inspiration(best_result, inspiration)
            result += "，建议刷" + best_result
        if len(card.valid_inspirations) > len(card.best_inspirations):
            valid_result = ""
            for inspiration in card.valid_inspirations.keys():
                if inspiration not in card.best_inspirations:
                    valid_result = append_inspiration(valid_result, inspiration)
            result += "，还可以刷" + valid_result
    if len(result) == 0:
        return "视实际用途刷"
    return result

def generate_card_md(card):
    result = '<table><tr><td colspan=6 style="background-color:#C0C0C0"><b>'+ (card.names if card.names else card.name) +'</b></td></tr>'
    result += '<tr>'
    result += '<td width="100px" style="text-align:center;" rowspan=7>'
    result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/card-avatar/' + card.name + '未觉.jpg" width="80px" />'
    result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/card-avatar/' + card.name + '.jpg" width="80px" />'
    result += '<td width="100px"><img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px" />' + str(card.ap) + '</td>'
    result += '<td width="400px"  colspan=4 rowspan=3>'
    result += "<b>个性1</b>：" + card.passive_scope + "基本"
    if card.passive_ap > 0.:
        result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/红值.png" width="20px"/>+' + str(round(100 * card.passive_ap, 1)) + "%"
    if card.passive_st > 0.:
        result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/绿值.png" width="20px"/>+' + str(round(100 * card.passive_st, 1)) + "%"
    if card.passive_te > 0.:
        result += '<img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/黄值.png" width="20px"/>+' + str(round(100 * card.passive_te, 1)) + "%"
    result += "<br>"
    # 个2
    result += "<b>个性2</b>："
    if card.actives[0]["trigger"] and card.actives[0]["type"] != "超充":
        result += card.actives[0]["trigger"] + "，"
    if card.actives[0]["trigger_rate"] < 1.:
        result += str(int(100 * card.actives[0]["trigger_rate"])) + "%概率"
    result += skill_text(card.actives[0]["type"], card.actives[0]["effect"], card.actives[0]["scope"], card.actives[0]["limit"], card.actives[0]["notes"])
    result += "<br>"
    # 特技
    result += "<b>特技</b>："
    if card.skill_trigger_rate == 0.11:
        result += "(11%发动率)"
    result += skill_text(card.skills[0]["type"], card.skills[0]["effect"], scope=card.skill_scope, notes=card.skill_notes)
    if len(card.skills) == 2:
        result += "，并" + skill_text(card.skills[1]["type"], card.skills[1]["effect"])
    
    result += '</td></tr>'
    result += '<tr><td><img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/绿值.png" width="20px" />'+str(card.st)+'</td></tr>'
    if card.te > card.ap and card.te > card.st:
        result += '<tr><td><img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/黄值.png" width="20px" /><b>'+str(card.te)+'</b></td></tr>'
    else:
        result += '<tr><td><img src="https://llas-1315296209.cos.ap-shanghai.myqcloud.com/resources/黄值.png" width="20px" />'+str(card.te)+'</td></tr>'
    result += '<tr style="text-align:center;background-color:#C0C0C0"><td width="100px"><b>综合评分</b></td><td width="100px"><b>绊板价值</b></td><td colspan=3 width="240px"><b>合宿推荐</b></td></tr>'
    card_final_rank = get_score_level(ranking_scores, card.final_score, ranking_levels)
    result += '<tr style="text-align:center;"><td>' + str(int(card.final_score)) + " (" + card_final_rank +')</td><td>' + get_kizuna_value_text(card) +'</td><td colspan=3>'+ generate_inspirations(card) +'</td></tr>'
    result += '<tr><td colspan=5 style="text-align:center;background-color:#C0C0C0" width="400px"><b>简评</b></td></tr>'
    result += '<tr><td colspan=5 style="text-align:center;">'
    # 评价
    result += get_assessment(card)
    #result += str(card.scores) # debug打开这一行
    result += '</td></tr>'
    result += '<tr><td colspan=6 style="text-align:center;background-color:#C0C0C0"><b>能力</b></td></tr>'
    result += '<tr style="text-align:center;">'
    result += '<td width="100px"><b>上级<br>前排输出</b></td>'
    result += '<td width="100px"><b>上+<br>前排输出</b></td>'
    result += '<td width="100px"><b>无上限<br>前排输出</b></td>'
    if card.support_same_attribute_average > card.support_all_average + 0.01:
        result += '<td width="100px"><b><span style="color:' + color_code[card.color] + '">' + card.color + '队</span><br>后排辅助</b></td>'
    else:
        result += '<td width="100px"><b>通用<br>后排辅助</b></td>'
    result += '<td width="100px"><b>奶盾</b></td>'
    result += '<td width="100px"><b>其他</b></td>'
    result += '</tr>'
    result += '<tr style="text-align:center;">'

    score_tmp = card.power['上级']["average"] / base_damage['上级']
    score_level = get_score_level(levels_score["上级输出"], score_tmp, card_levels)
    result += '<td width="100px"><span style="font-size:30px;">' + format_score_level(score_level) + '</span><br>'
    result += str(round(score_tmp, 1))
    result += '<br>(' +str(int(card.power['上级']["low"] / base_damage['上级']))+ "→" + str(int(card.power['上级']["very-high"] / base_damage['上级'])) +')'
    result += "</td>"

    score_tmp = card.power['上级+']["average"] / base_damage['上级+']
    score_level = get_score_level(levels_score["上级+输出"], score_tmp, card_levels)
    result += '<td width="100px"><span style="font-size:30px;">' + format_score_level(score_level) + '</span><br>'
    result += str(round(card.power['上级+']["average"] / base_damage['上级+'], 1))
    result += '<br>(' +str(int(card.power['上级+']["low"] / base_damage['上级+']))+ "→" + str(int(card.power['上级+']["very-high"] / base_damage['上级+'])) +')'
    result += "</td>"

    score_tmp = card.power['无上限']["average"] / base_damage['无上限']
    score_level = get_score_level(levels_score["无上限输出"], score_tmp, card_levels)
    result += '<td width="100px"><span style="font-size:30px;">' + format_score_level(score_level) + '</span><br>'
    result += str(round(card.power['无上限']["average"] / base_damage['无上限'], 1))
    result += '<br>(' +str(int(card.power['无上限']["low"] / base_damage['无上限']))+ "→" + str(int(card.power['无上限']["very-high"] / base_damage['无上限'])) +')'
    result += "</td>"
    
    if get_support(card, card.color) > get_support(card) + 0.01:
        score_level = get_score_level(levels_score["后排辅助"], (get_support(card, card.color) + get_support(card, card.color, True)) / 2, card_levels)
        result += '<td width="100px"><span style="font-size:30px;">' + format_score_level(score_level) + '</span><br>'
        result += "平均" + str(round(100 * get_support(card, card.color), 1)) + "%"
        result += "<br>上限" + str(round(100 * get_support(card, card.color, True), 1)) + "%"
    else:
        score_level = get_score_level(levels_score["后排辅助"], (get_support(card) + get_support(card, is_max=True)) / 2, card_levels)
        result += '<td width="100px"><span style="font-size:30px;">' + format_score_level(score_level) + '</span><br>'
        result += "平均" + str(round(100 * get_support(card), 1)) + "%"
        result += "<br>上限" + str(round(100 * get_support(card, is_max=True), 1)) + "%"
    result += "</td>"

    score_level_main = get_score_level(levels_score["前排奶盾"], card.get_heal_main(), card_levels)
    score_level_swap = get_score_level(levels_score["切队奶盾"], card.get_heal_swap(), card_levels)
    score_level_back = get_score_level(levels_score["后排奶盾"], (card.heal["上级"]["back"] + card.heal["上级+"]["back"]) / 2, card_levels)
    result += '<td width="100px"><span style="font-size:20px;">'
    is_first = True
    if score_level_main != "-":
        result += '前排' + format_score_level(score_level_main)
        is_first = False
    if score_level_swap != "-":
        if not is_first:
            result += "<br>"
        result += '切队' + format_score_level(score_level_swap)
        is_first = False
    if score_level_back != "-":
        if not is_first:
            result += "<br>"
        result += '后排' + format_score_level(score_level_back)
        is_first = False
    if is_first:
        result += "-"
    result += '</span></td>'

    is_first = True
    result += '<td width="100px"><span style="font-size:15px;">'
    score_damage_reduction = get_score_level(levels_score["减伤"], card.scores["减伤"], card_levels)
    score_support_magical_all = get_score_level(levels_score["后排爆分"], card.scores["通用后排爆分"], card_levels)
    score_support_magical_same_attribute = get_score_level(levels_score["后排爆分"], card.scores["同属性后排爆分"], card_levels)
    if score_damage_reduction != "-":
        result += '减伤' + format_score_level(score_damage_reduction)
        is_first = False
    if score_support_magical_all != "-" and card.scores["同属性后排爆分"] <= card.scores["通用后排爆分"]:
        if not is_first:
            result += "<br>"
        result += '通用后排突破上限得分' + format_score_level(score_support_magical_all)
        is_first = False
    if score_support_magical_same_attribute != "-" and card.scores["同属性后排爆分"] > card.scores["通用后排爆分"]:
        if not is_first:
            result += "<br>"
        result += '同属性后排突破上限得分' + format_score_level(score_support_magical_same_attribute)
        is_first = False
    if "SBL抢赏" in card.scores.keys() and card.scores["SBL抢赏"] >= 30.:
        if not is_first:
            result += "<br>"
        result += 'SBL抢赏'
        is_first = False
    if "千伤回血" in card.scores.keys() and card.scores["千伤回血"] >= 30.:
        if not is_first:
            result += "<br>"
        result += '千伤回血'
        is_first = False
    if "同学校后排辅助爆分" in card.scores.keys() and card.scores["同学校后排辅助爆分"] >= 30.:
        if not is_first:
            result += "<br>"
        result += '同学校后排辅助爆分'
        is_first = False
    if "驱散" in card.scores.keys() and card.scores["驱散"] > 30.:
        if not is_first:
            result += "<br>"
        result += '驱散'
        is_first = False
    if "超充" in card.scores.keys() and card.scores["超充"] > 30.:
        if not is_first:
            result += "<br>"
        result += '超充'
        is_first = False
    if is_first:
        result += "-"
    result += '</span></td>'
    result += '</tr>'
    return result

def get_global_stat(cards):
    result = {}
    result["damage_sorted"] = {}
    for difficulty in ["上级", "上级+"]:
        result["damage_sorted"][difficulty] = {}
        cards = sorted(cards, key = lambda x: x.power[difficulty]["average"], reverse=True)
        for color in colors:
            result["damage_sorted"][difficulty][color] = []
            for card in cards:
                if card.color == color:
                    result["damage_sorted"][difficulty][color].append(card.power[difficulty]["average"])

    result["support"] = {}
    result["support"]["通用"] = []
    cards = sorted(cards, key = lambda x: (get_support(x, None, True) + get_support(x, None)) / 2, reverse=True)
    for card in cards:
        result["support"]["通用"].append((get_support(card, None, True) + get_support(card, None)) / 2)
    for color in colors:
        result["support"][color] = []
        cards = sorted(cards, key = lambda x: (get_support(x, color, True) + get_support(x, color)) / 2, reverse=True)
        for card in cards:
            result["support"][color].append((get_support(card, color, True) + get_support(card, color)) / 2)

    result["heal_back"] = []
    cards = sorted(cards, key = lambda x: get_back_heal(x), reverse=True)
    for card in cards:
        result["heal_back"].append(get_back_heal(card))

    result["heal_main"] = {}
    cards = sorted(cards, key = lambda x: x.get_heal_main(), reverse=True)
    for color in colors:
        result["heal_main"][color] = []
        for card in cards:
            if card.color == color:
                result["heal_main"][color].append(card.get_heal_main())

    result["heal_swap"] = {}
    cards = sorted(cards, key = lambda x: x.get_heal_swap(), reverse=True)
    for color in colors:
        result["heal_swap"][color] = []
        for card in cards:
            if card.color == color:
                result["heal_main"][color].append(card.get_heal_swap())
    return result

if __name__ == "__main__":
    from openpyxl import load_workbook, Workbook
    workbook = load_workbook("card_data.xlsx")
    sheet = workbook["Sheet1"]
    
    cards = []
    #difficulty = "advanced"

    for rownum in range(2, sheet.max_row + 1):
        card = Card()
        row = sheet[rownum]
        card.name = row[0].value
        card.color = row[1].value
        card.ap = int(row[2].value)
        card.st = int(row[3].value)
        card.te = int(row[4].value)
        card.card_type = row[5].value
        card.slot = int(row[6].value)
        if row[7].value:
            card.passive_ap = float(row[7].value)
        if row[8].value:
            card.passive_st = float(row[8].value)
        if row[9].value:
            card.passive_te = float(row[9].value)
        if row[10].value:
            card.passive_scope = row[10].value
        card.actives = [{"type": row[11].value, "effect": float(row[12].value), "trigger": "None", "scope":""}]
        card.actives[0]["notes"] = 0
        if row[13].value:
            card.actives[0]["notes"] = int(row[13].value)
        card.actives[0]["limit"] = 0
        if row[14].value:
            card.actives[0]["trigger"] = row[14].value
            if "/" in card.actives[0]["trigger"]:
                card.actives[0]["limit"] = int(card.actives[0]["trigger"].split("/")[1])
                card.actives[0]["trigger"] = card.actives[0]["trigger"].split("/")[0]
        if row[15].value:
            card.actives[0]["scope"] = row[15].value
        if row[16].value:
            card.actives[0]["trigger_rate"] = row[16].value
        else:
            card.actives[0]["trigger_rate"] = 1.
        card.skills = [{"type": row[17].value, "effect": row[18].value}]
        if row[19].value:
            card.skills.append({"type": row[19].value, "effect": row[20].value})
        card.skill_notes = 0
        if row[21].value:
            card.skill_notes = int(row[21].value)
        if row[22].value:
            card.skill_trigger_rate = float(row[22].value)
        if row[23].value:
            card.skill_scope = row[23].value
        if row[24].value:
            card.names = row[24].value
        if row[25].value:
            card.special_score = row[25].value
        for skill in card.skills:
            if type(skill["effect"]) == str and "/" not in skill["effect"]:
                skill["effect"] = float(skill["effect"])

        # 上级/上+强度计算
        card.power = {}
        card.support = {}
        card.heal = {}
        for difficulty in difficulties:
            results_average = 0
            card.power[difficulty] = {}
            card.debug[difficulty] = {}
            card.support[difficulty] = {}
            card.heal[difficulty] = {}
            card.debug[difficulty]["power_by_level"] = {}
            for level in levels.keys():
                team = TeamConfig()
                card.debug[difficulty]["power_by_level"][level] = {}
                best_accessory = ""
                best_damage = 0
                for accessory_level in accessory_levels:
                    if "high" in level and accessory_level == "low":
                        continue
                    team.set_level(level, accessory_level, difficulty, is_same_color=True)
                    card.calculate(team, song)
                    card.debug[difficulty]["power_by_level"][level][accessory_level] = {}
                    card.debug[difficulty]["power_by_level"][level][accessory_level]["attack"] = card.attack
                    card.debug[difficulty]["power_by_level"][level][accessory_level]["critical_rate"] = card.critical_rate
                    card.debug[difficulty]["power_by_level"][level][accessory_level]["physical"] = card.scoring
                    card.debug[difficulty]["power_by_level"][level][accessory_level]["teammate_critical"] = card.teammate_crit_scoring
                    card.debug[difficulty]["power_by_level"][level][accessory_level]["magical"] = card.magical
                    if card.average_note > best_damage:
                        best_damage = card.average_note
                        best_accessory = accessory_level

                card.debug[difficulty]["power_by_level"][level]["accessory"] = best_accessory
                team.set_level(level, best_accessory, difficulty, is_same_color=True)
                card.calculate(team, song)
                results_average += 1. * card.average_note * levels[level] / levels_total
                card.power[difficulty][level] = card.average_note
                if level == "mid-high":
                    card.support[difficulty]["all"] = card.support_all_average
                    card.support[difficulty]["same_attribute"] = card.support_same_attribute_average
                    card.support[difficulty]["all_max"] = card.support_all_max
                    card.support[difficulty]["same_attribute_max"] = card.support_same_attribute_max
                    card.heal[difficulty]["main"] = card.heal_main
                    card.heal[difficulty]["back"] = card.heal_back
                    card.heal[difficulty]["swap"] = card.heal_swap
            card.power[difficulty]["average"] = results_average
            
        cards.append(card)
        
        #print(card.name, int(card.attack), round(card.critical_rate, 2), int(card.scoring), int(card.teammate_crit_scoring), int(card.magical), int(card.average_note))

    global_stat = get_global_stat(cards)
    for card in cards:
        card.get_scoring(global_stat)

    workbook_result = Workbook()
    sheet_result = workbook_result.active
    sheet_result.append(["", "颜色", "平均"] + list(levels.keys()))
    for difficulty in difficulties:
        cards = sorted(cards, key=lambda x: x.power[difficulty]["average"], reverse=True)
        count = 0
        for card in cards:
            count += 1
            sheet_result.append([card.name, card.color, card.power[difficulty]["average"]] + [card.power[difficulty][level] for level in levels.keys()])
            if count < 0:
                print_level(card, difficulty)
        # 生成表格
        for color in ["粉", "绿", "蓝", "红", "黄", "紫"]:
            sheet_color = workbook_result.create_sheet(color + difficulty)
            sheet_color.append(["", "颜色", "平均"] + list(levels.keys()))
            for card in cards:
                if card.color == color:
                    sheet_color.append([card.name, card.color, card.power[difficulty]["average"]] + [card.power[difficulty][level] for level in levels.keys()])

        # 生成节奏榜图
        '''
        rank_levels = ["S", "A+", "A", "B+", "B"]

        font_title = ImageFont.truetype("simhei.ttf", 100)
        max_x = 2000
        max_y = 7900
        if difficulty == "上级+":
            levels_score = {"S": 100, "A+": 95, "A": 90, "B+": 85, "B": 80}
        elif difficulty == "上级":
            levels_score = {"S": 108, "A+": 105, "A": 102, "B+": 98, "B": 94}
            max_x = 1800
            max_y = 7900
        else: # 无上限
            levels_score = {"S": 100, "A+": 95, "A": 90, "B+": 85, "B": 80, "C+": 75, "C": 70}
            rank_levels = ["S", "A+", "A", "B+", "B", "C+", "C"]
            max_x = 1800
            max_y = 10500
        background = Image.new("RGB", (max_x, max_y), (255, 255, 255))
        draw = ImageDraw.Draw(background)
        font_description = ImageFont.truetype("simhei.ttf", 50)
        font_author = ImageFont.truetype("simhei.ttf", 70)
        y = 300
        if difficulty == "上级+":
            draw.text((200, 50), difficulty+"前排输出榜（25w按键上限）", (0,0,0), font=font_title)
            draw.text((560, 180), "Bilibili：Glaceon_LL研究部", (0,0,0), font=font_author)
            base_y = 7340
            draw.text((250, base_y), "说明：1. 中间的数据为从低配到高配下的平均输出能力", (0,0,0), font=font_description)
            draw.text((475, base_y + 60), "该数值通常高于13层绊板，低于18层绊板的输出", (0,0,0), font=font_description)
            draw.text((400, base_y + 120), "2. 括号中的数据为低配时和顶配时的输出能力", (0,0,0), font=font_description)
            draw.text((475, base_y + 180), "用于表示卡片的成长率", (0,0,0), font=font_description)
            draw.text((400, base_y + 240), "3. 输出为100的含义是单键250000", (0,0,0), font=font_description)
        if difficulty == "上级":
            draw.text((200, 50), difficulty+"前排输出榜（10w按键上限）", (0,0,0), font=font_title)
            draw.text((410, 180), "Bilibili：Glaceon_LL研究部", (0,0,0), font=font_author)
            base_y = 7340
            draw.text((100, base_y + 60), "说明：1. 中间的数据为从低配到高配下的平均输出能力", (0,0,0), font=font_description)
            draw.text((325, base_y + 120), "该数值通常高于13层绊板，低于18层绊板的输出", (0,0,0), font=font_description)
            draw.text((250, base_y + 180), "2. 括号中的数据为低配时和顶配时的输出能力", (0,0,0), font=font_description)
            draw.text((325, base_y + 240), "用于表示卡片的成长率", (0,0,0), font=font_description)
            #draw.text((250, base_y + 300), "3. 上级的猜想环境是用满暴击率的同色超限sk和sp快充", (0,0,0), font=font_description)
            #draw.text((325, base_y + 360), "有时会用高暴击率的vo", (0,0,0), font=font_description)
            #draw.text((325, base_y + 420), "根据此进行的计算，最终环境一定会有偏差", (0,0,0), font=font_description)
            #draw.text((325, base_y + 480), "（例如超高绊板、SBL buff下的同色爆分卡和强力sp/sk跨色）", (0,0,0), font=font_description)
            draw.text((250, base_y + 300), "3. 输出为100的含义是单键130000", (0,0,0), font=font_description)
            #y += 80
        if difficulty == "无上限":
            draw.text((500, 50), difficulty+"前排输出榜", (0,0,0), font=font_title)
            draw.text((460, 180), "Bilibili：Glaceon_LL研究部", (0,0,0), font=font_author)
            base_y = 9800
            draw.text((250, base_y), "说明：1. 中间的数据为从低配到高配下的平均输出能力", (0,0,0), font=font_description)
            draw.text((475, base_y + 60), "该数值通常高于13层绊板，低于18层绊板的输出", (0,0,0), font=font_description)
            draw.text((400, base_y + 120), "2. 括号中的数据为低配时和顶配时的输出能力", (0,0,0), font=font_description)
            draw.text((475, base_y + 180), "用于表示卡片的成长率", (0,0,0), font=font_description)
            draw.text((400, base_y + 240), "3. 输出为100的含义是单键300000", (0,0,0), font=font_description)

        font = ImageFont.truetype("simhei.ttf", 50)
        font_score = ImageFont.truetype("simhei.ttf", 30)
        font_color = ImageFont.truetype("simhei.ttf", 100)
        x = 0
        

        for color in ["粉", "绿", "蓝", "红", "黄", "紫"]:
            x = 50
            
            y += 50

            draw.text((max_x / 2 - 140, y), color + "卡", colors[color], font=font_color)
            y += 150
            color_y = y

            for level in rank_levels:
                draw.text((x, y), level, (0,0,0), font=font)
                y += 200
            x = 150
            y = color_y - 40
            current_rank = 0
            for card in cards:
                if card.color == color:
                    card_score = int(card.power[difficulty]["average"] / base_damage[difficulty])
                    while current_rank <= len(levels_score) - 1 and card_score < levels_score[rank_levels[current_rank]]:
                        current_rank += 1
                        y += 200
                        x = 150
                    if current_rank >= len(levels_score):
                        break
                    try:
                        card_image = Image.open("images/" + card.name+ ".jpg")
                        background.paste(card_image, (x, y))
                    except:
                        pass
                    draw.text((x + 40 if current_rank == 0 else x + 50, y + 130), str(card_score), (0,0,0), font=font_score)
                    #draw.text((x + 40, y + 160), str(round(card.growth)), (0,0,0), font=font_score)
                    draw.text((x + 0, y + 160), "(" + str(int(card.power[difficulty]["low"] / base_damage[difficulty]))+ "→" + str(int(card.power[difficulty]["very-high"] / base_damage[difficulty])) + ")", (0,0,0), font=font_score)
                    x += 160
            while current_rank < 5:
                y += 200
                current_rank += 1

        #background.show()
        background.save(difficulty + "前排输出.jpg")
        '''
    workbook_result.save("强度计算.xlsx")

    '''
    debug = False
    characters = {}
    character_value = Image.new("RGBA", (1600 - (0 if debug else 160), 6800), (255, 255, 255))
    draw = ImageDraw.Draw(character_value)
    draw.text((380, 50), "角色绊板价值", (0,0,0), font=font_title)
    draw.text((260, 180), "Bilibili：Glaceon_LL研究部", (0,0,0), font=font_author)
    draw.text((480, 280), timestamp, (0,0,0), font=font_author)
    base_y = 6450
    draw.text((150, base_y), "说明：1. 绊板主要加成的是按键得分能力", (0,0,0), font=font_description)
    draw.text((375, base_y + 60), "所以绊板价值高的卡均为前排输出", (0,0,0), font=font_description)
    draw.text((300, base_y + 120), "2. 排序考虑了一名角色的所有卡片", (0,0,0), font=font_description)
    draw.text((375, base_y + 180), "实际要根据自己拥有的卡选择开绊板的角色", (0,0,0), font=font_description)
    draw.text((375, base_y + 240), "也要根据卡片颜色选择，优先补盲", (0,0,0), font=font_description)
    for card in cards:
        character = card.name[-1]
        if character in characters.keys():
            characters[character]["cards"].append(card)
        else:
            characters[character] = {"cards": [card], "value": 0., "character": character}
        characters[character]["value"] += card.get_value()
    characters_list = []
    for character in characters:
        characters_list.append(characters[character])
    characters_list = sorted(characters_list, key = lambda x: x["value"], reverse=True)
    font_ch_score = ImageFont.truetype("simhei.ttf", 25)
    font_value_1 = ImageFont.truetype("simhei.ttf", 40)
    font_value_2 = ImageFont.truetype("simhei.ttf", 35)
    font_value_3 = ImageFont.truetype("simhei.ttf", 30)
    font_value_4 = ImageFont.truetype("simhei.ttf", 25)
    font_value_5 = ImageFont.truetype("simhei.ttf", 20)
    font_value_6 = ImageFont.truetype("simhei.ttf", 15)
    y = 400
    for character in characters_list:
        x = 50
        #character_image = Image.open("characters\\" + character["character"] + ".png")
        character_image = Image.open("characters/" + character["character"] + ".png")
        character_value.paste(character_image, (x, y))
        x += 120
        if debug:
            draw.text((x, y), str(round(character["value"], 2)), (0,0,0), font=font)
            x += 140
        character["cards"] = sorted(character["cards"], key=lambda x: x.get_value(), reverse=True)
        for card in character["cards"]:
            if card.get_value() <= 0.1:
                continue
            card_image = None
            try:
                card_image = Image.open("images/" + card.name + ".jpg")
                character_value.paste(card_image, (x, y))
            except:
                pass
            #card_score = int(card.power["average"] / base_damage)
            #draw.text((x + 40 if current_rank == 0 else x + 50, y + 130), str(card_score), (0,0,0), font=font_score)
            y_ = y
            if debug:
                if card.expert_score > 0.:
                    draw.text((x + 0, y + 130), "上+：" + str(round(card.expert_score, 2)), (0,0,0), font=font_ch_score)
                    y_ += 20
                if card.advanced_score > 0.:
                    draw.text((x + 0, y_ + 130), "上级：" + str(round(card.advanced_score, 2)), (0,0,0), font=font_ch_score)
                    y_ += 20
                if card.healer_score > 0.:
                    draw.text((x + 0, y_ + 130), "奶盾：" + str(round(card.healer_score, 2)), (0,0,0), font=font_ch_score)
                    y_ += 20
                if card.sbl_score > 0.:
                    draw.text((x + 0, y_ + 130), "SBL：" + str(round(card.sbl_score, 2)), (0,0,0), font=font_ch_score)
                    y_ += 20
            else:
                x_offset = 24
                y_offset = 135
                if card.get_value() >= 2.:
                    draw.text((x + 25, y + 135), "超高", (255,0,0), font=font_value_1)
                elif card.get_value() >= 1.5:
                    draw.text((x + 28, y + 137), "很高", (255,0,0), font=font_value_2)
                elif card.get_value() >= 1.:
                    draw.text((x + 31, y + 140), "较高", (255,0,0), font=font_value_3)
                elif card.get_value() >= 0.6:
                    draw.text((x + 31, y + 140), "中上", (0,0,0), font=font_value_3)
                elif card.get_value() >= 0.3:
                    draw.text((x + 35, y + 143), "中等", (0,0,0), font=font_value_4)
                elif card.get_value() >= 0.1:
                    draw.text((x + 39, y + 145), "略有", (0,0,0), font=font_value_5)
            x += 160
        y += 200

    #character_value.show()
    character_value.save("角色绊板价值.png")
    '''

    # 分档表
    writefile = codecs.open("result/全卡综合强度表.md", "w", "utf-8")
    writefile.write(generating_final_ranking_md(cards))
    writefile.close()
    writefile = codecs.open("result/全卡综合强度表_未觉.md", "w", "utf-8")
    writefile.write(generating_final_ranking_md(cards, idolized=False))
    writefile.close()

    # 输出
    for difficulty in ["上级", "上级+", "无上限"]:
        result = "# 说明\n\n"
        result += "1. 中间的数据为从低配到高配下的平均输出能力，该数值通常高于13层绊板，低于18层绊板的输出\n\n"
        result += "2. 括号中的数据为低配时和顶配时的输出能力，用于表示卡片的成长率\n\n"
        if difficulty == "上级":
            result += "3. 输出为100的含义是单键130000\n\n"
        elif difficulty == "上级+":
            result += "3. 输出为100的含义是单键250000\n\n"
        elif difficulty == "无上限":
            result += "3. 输出为100的含义是单键300000\n\n"
        for color in colors:
            result += "\n# " + color +"卡\n\n"
            result += generate_ranking_md(cards, difficulty + "输出", color=color)
        result += "\n# 全卡\n\n"
        result += generate_ranking_md(cards, difficulty + "输出")

        writefile = codecs.open("result/" + difficulty.replace("+", "＋") + "输出榜.md", "w", "utf-8")
        writefile.write(result)
        writefile.close()

    # 辅助
    result = "# 说明\n\n"
    result += "1. 数值为卡片在后排时，对前排输出能力的边际提升量。例如一个成型的队伍一般被动红值加成在100%左右，故1%被动红值计算稀释后，对输出的边际提升量为0.5%。\n\n"
    result += "2. “上限”的计算方法为：一次性触发的个性2都在第一次判定时触发；SP发动时50%概率触发的个性2（例如警察鸟、fes2彼）按75%触发率计算\n\n"
    result += "3. 部分SP发动时触发的加红值个性2存在溢出问题（即SP发动后加成较高，已经能够打到按键上限，个性2增加的红值未能够提升最终的得分），因此警察鸟的个性2按20%溢出计算，fes2璃、fes3妮花的个性2按40%溢出计算\n\n"
    result += "# 通用\n"
    result += generate_support_ranking_md(cards)
    for color in colors:
        result += "\n# " + color +"队\n\n"
        result += generate_support_ranking_md(cards, color=color)
    writefile = codecs.open("result/后排辅助榜.md", "w", "utf-8")
    writefile.write(result)
    writefile.close()

    # 奶盾
    result = "# 说明\n\n"
    result += "1. 前排奶盾的评分主要考虑和奶盾的量。因为过量的奶盾没有任何收益，奶盾量超过单键500后对评分的贡献会衰减计算\n\n"
    result += "2. 数值为评分，无物理含义\n\n"
    for color in colors:
        result += "\n# " + color +"卡\n\n"
        result += generate_main_healer_md(cards, color=color)
    result += "\n# 全卡\n\n"
    result += generate_main_healer_md(cards)
    writefile = codecs.open("result/前排奶盾榜.md", "w", "utf-8")
    writefile.write(result)
    writefile.close()

    result = "# 说明\n\n"
    result += "1. 切队奶盾的评分主要考虑后排辅助能力和奶盾的量，次要考虑输出能力\n\n"
    result += "2. 数值为评分，无物理含义\n\n"
    for color in colors:
        result += "\n# " + color +"卡\n\n"
        result += generate_swap_healer_md(cards, color=color)
    result += "\n# 全卡\n\n"
    result += generate_swap_healer_md(cards)
    writefile = codecs.open("result/切队奶盾榜.md", "w", "utf-8")
    writefile.write(result)
    writefile.close()

    result = "# 说明\n\n"
    result += "1. 数值为卡片在后排时能提供的单键治疗量\n\n"
    result += "2. 计算时考虑了自身绿值的25%。因为手镯、胸针等饰品和血量有关，未按30%考虑\n\n"
    result += "3. 暂时移除花园绘，未来分开平均和上限后再加回来\n\n"
    result += generate_back_healer_md(cards)
    writefile = codecs.open("result/后排奶盾榜.md", "w", "utf-8")
    writefile.write(result)
    writefile.close()

    # 绊板价值
    characters = {}
    for card in cards:
        character = card.name[-1]
        if character in characters.keys():
            characters[character]["cards"].append(card)
        else:
            characters[character] = {"cards": [card], "value": 0., "character": character}
        characters[character]["value"] += card.get_value()
    characters_list = []
    for character in characters:
        characters_list.append(characters[character])
    characters_list = sorted(characters_list, key = lambda x: x["value"], reverse=True)
    # 角色绊板价值
    result = "# 说明\n\n"
    result += "1. 绊板主要加成的是按键得分能力，所以绊板价值高的卡均为前排卡。绊板对切队奶、后排奶会有少量加成，略微有一些绊板价值。绊板对后排辅助能力完全无加成，无绊板价值\n\n"
    result += "2. 排序考虑了一名角色的所有卡片，实际要根据自己拥有的卡选择开绊板的角色，也要根据卡片颜色选择，优先补盲\n\n"
    result += generate_kizuna_value_md(cards, characters_list)
    writefile = codecs.open("result/角色绊板价值.md", "w", "utf-8")
    writefile.write(result)
    writefile.close()

    # 全UR评价表
    '''
    writefile1 = codecs.open("result/新卡评价.md", "w", "utf-8")
    result_new = ""
    for card in cards:
        if card.name in ["p雫", "p绘"]:
            result_new += generate_card_md(card)
    writefile1.write(result_new)
    writefile1.close()
    '''

    cards = sorted(cards, key=lambda x: x.final_score, reverse=True)
    for character in characters_list:
        character["cards"] = sorted(character["cards"], key=lambda x: x.final_score, reverse=True)
        result = ""
        result += "\n" + generating_final_ranking_md(character["cards"]) + "\n"
        if character["character"] not in full_names.keys():
            continue
        for card in character["cards"]:
            result += generate_card_md(card)
        
        writefile = codecs.open("result/全卡评价表/" + full_names[character["character"]][0] + "-" +full_names[character["character"]][1]+".md", "w", "utf-8")
        writefile.write(result)
        writefile.close()
    

